ICT Immediate Rebalance [LuxAlgo]The ICT Immediate Rebalance aims at detecting and highlighting immediate rebalances, a concept taught by Inner Circle Trader. The ICT Immediate Rebalance, although frequently overlooked, emerges as one of ICT's most influential concepts, particularly when considered within a specific context.
🔶 USAGE
Immediate rebalances, a concept taught by ICT, hold significant importance in decision-making. To comprehend the concept of immediate rebalance, it's essential to grasp the notion of the fair value gap. A fair value gap arises from market inefficiencies or imbalances, whereas an immediate rebalance leaves no gap, no inefficiencies, or no imbalances that the price would need to return to.
Following an immediate rebalance, the typical expectation is for two extension candles to ensue; failing this, the immediate rebalance is deemed unsuccessful. It's important to note that both failed and successful immediate rebalances hold significance in trading when analyzed within a contextual framework.
Immediate rebalances can manifest across various locations and timeframes. It's recommended to analyze them in conjunction with other ICT tools or technical indicators to gain a more comprehensive understanding of market dynamics.
🔹 Multi Timeframe
The script facilitates multi-timeframe analysis, enabling users to display immediate rebalances from higher timeframes.
Enabling the display of higher timeframe candles helps visualize the detected immediate rebalance patterns.
🔹 Dashboard
The dashboard offers statistical insights into immediate rebalances.
🔶 SETTINGS
🔹 Immediate Rebalances
Timeframe: this option is to identify immediate rebalances from higher timeframes. If a timeframe lower than the chart's timeframe is selected, calculations will be based on the chart's timeframe.
Bullish, and Bearish Immediate Rebalances: color customization options.
Wicks 75%, %50, and %25: color customization options of the wick price levels for the detected immediate rebalances.
Immediate Rebalance Candles: toggles the visualization of higher timeframe candles where immediate rebalance is detected.
Confirmation (Bars): specifies the number of bars required to confirm the validation of the detected immediate rebalance.
Immediate Rebalance Icon: allows customization of the size of the icon used to represent the immediate rebalance.
🔹 Dashboard
Dashboard: toggles the visualization of the dashboard, sets its location, and customizes the size of the dashboard.
🔶 RELATED SCRIPTS
Fair-Value-Gap
Thanks to our community for recommending this script. For more conceptual scripts and related content, we welcome you to explore by visiting >>> LuxAlgo-Scripts .
Wyszukaj w skryptach "THE SCRIPT"
CCOMET_Scanner_LibraryLibrary "CCOMET_Scanner_Library"
- A Trader's Edge (ATE)_Library was created to assist in constructing CCOMET Scanners
Loc_tIDs_Col(_string, _firstLocation)
TickerIDs: You must form this single tickerID input string exactly as described in the scripts info panel (little gray 'i' that
is circled at the end of the settings in the settings/input panel that you can hover your cursor over this 'i' to read the
details of that particular input). IF the string is formed correctly then it will break up this single string parameter into
a total of 40 separate strings which will be all of the tickerIDs that the script is using in your CCOMET Scanner.
Locations: This function is used when there's a desire to print an assets ALERT LABELS. A set Location on the scale is assigned to each asset.
This is created so that if a lot of alerts are triggered, they will stay relatively visible and not overlap each other.
If you set your '_firstLocation' parameter as 1, since there are a max of 40 assets that can be scanned, the 1st asset's location
is assigned the value in the '_firstLocation' parameter, the 2nd asset's location is the (1st asset's location+1)...and so on.
Parameters:
_string (simple string) : (string)
A maximum of 40 Tickers (ALL joined as 1 string for the input parameter) that is formulated EXACTLY as described
within the tooltips of the TickerID inputs in my CCOMET Scanner scripts:
assets = input.text_area(tIDset1, title="TickerID (MUST READ TOOLTIP)", tooltip="Accepts 40 TICKERID's for each
copy of the script on the chart. TEXT FORMATTING RULES FOR TICKERID'S:
(1) To exclude the EXCHANGE NAME in the Labels, de-select the next input option.
(2) MUST have a space (' ') AFTER each TickerID.
(3) Capitalization in the Labels will match cap of these TickerID's.
(4) If your asset has a BaseCurrency & QuoteCurrency (ie. ADAUSDT ) BUT you ONLY want Labels
to show BaseCurrency(ie.'ADA'), include a FORWARD SLASH ('/') between the Base & Quote (ie.'ADA/USDT')", display=display.none)
_firstLocation (simple int) : (simple int)
Optional (starts at 1 if no parameter added).
Location that you want the first asset to print its label if is triggered to do so.
ie. loc2=loc1+1, loc3=loc2+1, etc.
Returns: Returns 40 output variables in the tuple (ie. between the ' ') with the TickerIDs, 40 variables for the locations for alert labels, and 40 Colors for labels/plots
TickeridForLabelsAndSecurity(_ticker, _includeExchange)
This function accepts the TickerID Name as its parameter and produces a single string that will be used in all of your labels.
Parameters:
_ticker (simple string) : (string)
For this parameter, input the varible named '_coin' from your 'f_main()' function for this parameter. It is the raw
Ticker ID name that will be processed.
_includeExchange (simple bool) : (bool)
Optional (if parameter not included in function it defaults to false ).
Used to determine if the Exchange name will be included in all labels/triggers/alerts.
Returns: ( )
Returns 2 output variables:
1st ('_securityTickerid') is to be used in the 'request.security()' function as this string will contain everything
TV needs to pull the correct assets data.
2nd ('lblTicker') is to be used in all of the labels in your CCOMET Scanner as it will only contain what you want your labels
to show as determined by how the tickerID is formulated in the CCOMET Scanner's input.
InvalID_LblSz(_barCnt, _close, _securityTickerid, _invalidArray, _tablePosition, _stackVertical, _lblSzRfrnce)
INVALID TICKERIDs: This is to add a table in the middle right of your chart that prints all the TickerID's that were either not formulated
correctly in the '_source' input or that is not a valid symbol and should be changed.
LABEL SIZES: This function sizes your Alert Trigger Labels according to the amount of Printed Bars the chart has printed within
a set time period, while also keeping in mind the smallest relative reference size you input in the 'lblSzRfrnceInput'
parameter of this function. A HIGHER % of Printed Bars(aka...more trades occurring for that asset on the exchange),
the LARGER the Name Label will print, potentially showing you the better opportunities on the exchange to avoid
exchange manipulation liquidations.
*** SHOULD NOT be used as size of labels that are your asset Name Labels next to each asset's Line Plot...
if your CCOMET Scanner includes these as you want these to be the same size for every asset so the larger ones dont cover the
smaller ones if the plots are all close to each other ***
Parameters:
_barCnt (float) : (float)
Get the 1st variable('barCnt') from the Security function's tuple and input it as this functions 1st input
parameter which will directly affect the size of the 2nd output variable ('alertTrigLabel') that is also outputted by this function.
_close (float) : (float)
Put your 'close' variable named '_close' from the security function here.
_securityTickerid (string) : (string)
Throughout the entire charts updates, if a '_close' value is never registered then the logic counts the asset as INVALID.
This will be the 1st TickerID variable (named _securityTickerid) outputted from the tuple of the TickeridForLabels()
function above this one.
_invalidArray (array) : (array string)
Input the array from the original script that houses all of the invalidArray strings.
_tablePosition (simple string) : (string)
Optional (if parameter not included, it defaults to position.middle_right). Location on the chart you want the table printed.
Possible strings include: position.top_center, position.top_left, position.top_right, position.middle_center,
position.middle_left, position.middle_right, position.bottom_center, position.bottom_left, position.bottom_right.
_stackVertical (simple bool) : (bool)
Optional (if parameter not included, it defaults to true). All of the assets that are counted as INVALID will be
created in a list. If you want this list to be prited as a column then input 'true' here, otherwise they will all be in a row.
_lblSzRfrnce (string) : (string)
Optional (if parameter not included, it defaults to size.small). This will be the size of the variable outputted
by this function named 'assetNameLabel' BUT also affects the size of the output variable 'alertTrigLabel' as it uses this parameter's size
as the smallest size for 'alertTrigLabel' then uses the '_barCnt' parameter to determine the next sizes up depending on the "_barCnt" value.
Returns: ( )
Returns 2 variables:
1st output variable ('AssetNameLabel') is assigned to the size of the 'lblSzRfrnceInput' parameter.
2nd output variable('alertTrigLabel') can be of variying sizes depending on the 'barCnt' parameter...BUT the smallest
size possible for the 2nd output variable ('alertTrigLabel') will be the size set in the 'lblSzRfrnceInput' parameter.
PrintedBarCount(_time, _barCntLength, _barCntPercentMin)
The Printed BarCount Filter looks back a User Defined amount of minutes and calculates the % of bars that have printed
out of the TOTAL amount of bars that COULD HAVE been printed within the same amount of time.
Parameters:
_time (int) : (int)
The time associated with the chart of the particular asset that is being screened at that point.
_barCntLength (int) : (int)
The amount of time (IN MINUTES) that you want the logic to look back at to calculate the % of bars that have actually
printed in the span of time you input into this parameter.
_barCntPercentMin (int) : (int)
The minimum % of Printed Bars of the asset being screened has to be GREATER than the value set in this parameter
for the output variable 'bc_gtg' to be true.
Returns: ( )
Returns 2 outputs:
1st is the % of Printed Bars that have printed within the within the span of time you input in the '_barCntLength' parameter.
2nd is true/false according to if the Printed BarCount % is above the threshold that you input into the '_barCntPercentMin' parameter.
Dividend Calendar (Zeiierman)█ Overview
The Dividend Calendar is a financial tool designed for investors and analysts in the stock market. Its primary function is to provide a schedule of expected dividend payouts from various companies.
Dividends, which are portions of a company's earnings distributed to shareholders, represent a return on their investment. This calendar is particularly crucial for investors who prioritize dividend income, as it enables them to plan and manage their investment strategies with greater effectiveness. By offering a comprehensive overview of when dividends are due, the Dividend Calendar aids in informed decision-making, allowing investors to time their purchases and sales of stocks to optimize their dividend income. Additionally, it can be a valuable tool for forecasting cash flow and assessing the financial health and dividend-paying consistency of different companies.
█ How to Use
Dividend Yield Analysis:
By tracking dividend growth and payouts, traders can identify stocks with attractive dividend yields. This is particularly useful for income-focused investors who prioritize steady cash flow from their investments.
Income Planning:
For those relying on dividends as a source of income, the calendar helps in forecasting income.
Trend Identification:
Analyzing the growth rates of dividends helps in identifying long-term trends in a company's financial health. Consistently increasing dividends can be a sign of a company's strong financial position, while decreasing dividends might signal potential issues.
Portfolio Diversification:
The tool can assist in diversifying a portfolio by identifying a range of dividend-paying stocks across different sectors. This can help mitigate risk as different sectors may react differently to market conditions.
Timing Investments:
For those who follow a dividend capture strategy, this indicator can be invaluable. It can help in timing the buying and selling of stocks around their ex-dividend dates to maximize dividend income.
█ How it Works
This script is a comprehensive tool for tracking and analyzing stock dividend data. It calculates growth rates, monthly and yearly totals, and allows for custom date handling. Structured to be visually informative, it provides tables and alerts for the easy monitoring of dividend-paying stocks.
Data Retrieval and Estimation: It fetches dividend payout times and amounts for a list of stocks. The script also estimates future values based on historical data.
Growth Analysis: It calculates the average growth rate of dividend payments for each stock, providing insights into dividend consistency and growth over time.
Summation and Aggregation: The script sums up dividends on a monthly and yearly basis, allowing for a clear view of total payouts.
Customization and Alerts: Users can input custom months for dividend tracking. The script also generates alerts for upcoming or current dividend payouts.
Visualization: It produces various tables and visual representations, including full calendar views and income tables, to display the dividend data in an easily understandable format.
█ Settings
Overview:
Currency:
Description: This setting allows the user to specify the currency in which dividend values are displayed. By default, it's set to USD, but users can change it to their local currency.
Impact: Changing this value alters the currency denomination for all dividend values displayed by the script.
Ex-Date or Pay-Date:
Description: Users can select whether to show the Ex-dividend day or the Actual Payout day.
Impact: This changes the reference date for dividend data, affecting the timing of when dividends are shown as due or paid.
Estimate Forward:
Description: Enables traders to predict future dividends based on historical data.
Impact: When enabled, the script estimates future dividend payments, providing a forward-looking view of potential income.
Dividend Table Design:
Description: Choose between viewing the full dividend calendar, just the cumulative monthly dividend, or a summary view.
Impact: This alters the format and extent of the dividend data displayed, catering to different levels of detail a user might require.
Show Dividend Growth:
Description: Users can enable dividend growth tracking over a specified number of years.
Impact: When enabled, the script displays the growth rate of dividends over the selected number of years, providing insight into dividend trends.
Customize Stocks & User Inputs:
This setting allows users to customize the stocks they track, the number of shares they hold, the dividend payout amount, and the payout months.
Impact: Users can tailor the script to their specific portfolio, making the dividend data more relevant and personalized to their investments.
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
signal_datagramThe purpose of this library is to split and merge an integer into useful pieces of information that can easily handled and plotted.
The basic piece of information is one word. Depending on the underlying numerical system a word can be a bit, octal, digit, nibble, or byte.
The user can define channels. Channels are named groups of words. Multiple words can be combined to increase the value range of a channel.
A datagram is a description of the user-defined channels in an also user-defined numeric system that also contains all runtime information that is necessary to split and merge the integer.
This library simplifies the communication between two scripts by allowing the user to define the same datagram in both scripts.
On the sender's side, the channel values can be merged into one single integer value called signal. This signal can be 'emitted' using the plot function. The other script can use the 'input.source' function to receive that signal.
On the receiver's end based on the same datagram, the signal can be split into several channels. Each channel has the piece of information that the sender script put.
In the example of this library, we use two channels and we have split the integer in half. However, the user can add new channels, change them, and give meaning to them according to the functionality he wants to implement and the type of information he wants to communicate.
Nowadays many 'input.source' calls are allowed to pass information between the scripts, When that is not a price or a floating value, this library is very useful.
The reason is that most of the time, the convention that is used is not clear enough and it is easy to do things the wrong way or break them later on.
With this library validation checks are done during the initialization minimizing the possibility of error due to some misconceptions.
Library "signal_datagram"
Conversion of a datagram type to a signal that can be "send" as a single value from an indicator to a strategy script
method init(this, positions, maxWords)
init - Initialize if the word positons array with an empty array
Namespace types: WordPosArray
Parameters:
this (WordPosArray) : - The word positions array object
positions (int ) : - The array that contains all the positions of the worlds that shape the channel
maxWords (int) : - The maximum words allowed based on the span
Returns: The initialized object
method init(this)
init - Initialize if the channels word positons map with an empty map
Namespace types: ChannelDesc
Parameters:
this (ChannelDesc) : - The channels' descriptor object
Returns: The initialized object
method init(this, numericSystem, channelDesc)
init - Initialize if the datagram
Namespace types: Datagram
Parameters:
this (Datagram) : - The datagram object
numericSystem (simple string) : - The numeric system of the words to be used
channelDesc (ChannelDesc) : - The channels descriptor that contains the positions of the words that each channel consists of
Returns: The initialized object
method add_channel(this, name, positions)
add_channel - Add a new channel descriptopn with its name and its corresponding word positons to the map
Namespace types: ChannelDesc
Parameters:
this (ChannelDesc) : - The channels' descriptor object to update
name (simple string)
positions (int )
Returns: The initialized object
method set_signal(this, value)
set_signal - Set the signal value
Namespace types: Datagram
Parameters:
this (Datagram) : - The datagram object to update
value (int) : - The signal value to set
method get_signal(this)
get_signal - Get the signal value
Namespace types: Datagram
Parameters:
this (Datagram) : - The datagram object to query
Returns: The value of the signal in digits
method set_signal_sign(this, sign)
set_signal_sign - Set the signal sign
Namespace types: Datagram
Parameters:
this (Datagram) : - The datagram object to update
sign (int) : - The negative -1 or positive 1 sign of the underlying value
method get_signal_sign(this)
get_signal_sign - Get the signal sign
Namespace types: Datagram
Parameters:
this (Datagram) : - The datagram object to query
Returns: The sign of the signal value -1 if it is negative and 1 if it is possitive
method get_channel_names(this)
get_channel_names - Get an array of all channel names
Namespace types: Datagram
Parameters:
this (Datagram)
Returns: An array that has all the channel names that are used by the datagram
method set_channel_value(this, channelName, value)
set_channel_value - Set the value of the channel
Namespace types: Datagram
Parameters:
this (Datagram) : - The datagram object to update
channelName (simple string) : - The name of the channel to set the value to. Then name should be as described int the schemas channel descriptor
value (int) : - The channel value to set
method set_all_channels_value(this, value)
set_all_channels_value - Set the value of all the channels
Namespace types: Datagram
Parameters:
this (Datagram) : - The datagram object to update
value (int) : - The channel value to set
method set_all_channels_max_value(this)
set_all_channels_value - Set the value of all the channels
Namespace types: Datagram
Parameters:
this (Datagram) : - The datagram object to update
method get_channel_value(this, channelName)
get_channel_value - Get the value of the channel
Namespace types: Datagram
Parameters:
this (Datagram) : - The datagram object to query
channelName (simple string)
Returns: Digit group of words (bits/octals/digits/nibbles/hexes/bytes) found at the channel accodring to the schema
WordDesc
Fields:
numericSystem (series__string)
span (series__integer)
WordPosArray
Fields:
positions (array__integer)
ChannelDesc
Fields:
map (map__series__string:|WordPosArray|#OBJ)
Schema
Fields:
wordDesc (|WordDesc|#OBJ)
channelDesc (|ChannelDesc|#OBJ)
Signal
Fields:
value (series__integer)
isNegative (series__bool)
words (array__integer)
Datagram
Fields:
schema (|Schema|#OBJ)
signal (|Signal|#OBJ)
ZigZag█ OVERVIEW
This library is a Pine Script™ programmer’s tool containing custom user-defined types and functions to calculate Zig Zag indicators within their scripts. It is not a stand-alone indicator.
Pine Script™ libraries are publications that contain reusable code for importing into Pine Script™ indicators, strategies, and other libraries. For more information on libraries and incorporating them into your scripts, see the Libraries section of the Pine Script™ User Manual .
█ CONCEPTS
Zig Zag
Zig Zag is a popular indicator that filters out minor price fluctuations to denoise data and emphasize trends. Traders commonly use Zig Zag for trend confirmation, identifying potential support and resistance, and pattern detection. It is formed by identifying significant local high and low points in alternating order and connecting them with straight lines, omitting all other data points from their output. There are several ways to calculate the Zig Zag's data points and the conditions by which its direction changes. This script uses pivots as the data points, which are the highest or lowest values over a defined number of bars before and after them. The direction only reverses when a newly formed pivot deviates from the last Zig Zag point in the opposite direction by an amount greater than or equal to a specified percentage.
To learn more about Zig Zag and how to calculate it, see this entry from the Help Center.
█ FOR Pine Script™ CODERS
Notes
This script's architecture utilizes user-defined types (UDTs) to create custom objects which are the equivalent of variables containing multiple parts, each able to hold independent values of different types . UDTs are the newest addition to Pine Script™ and the most advanced feature the language has seen to date. The feature's introduction creates a new runway for experienced coders to push the boundaries of Pine. We recommend that newcomers to the language explore the basics first before diving into UDTs and objects.
Demonstration Code
Our example code shows a simple use case by displaying a Zig Zag with user-defined settings. A new ZigZag object is instantiated on the first bar using a Settings object to control its attributes. The fields for the Settings object are declared using variables assigned to input.* functions, allowing control of the field values from the script's settings. The `update()` function is invoked on each bar to update the ZigZag object's fields and create new lines and labels when required.
Look first. Then leap.
█ TYPES
This library contains the following types:
Settings
Provides calculation and display attributes to ZigZag objects.
Fields:
devThreshold : The minimum percentage deviation from a point before the ZigZag will change direction.
depth : The number of bars required for pivot detection.
lineColor : Line color.
extendLast : Condition allowing a line to connect the most recent pivot with the current close.
displayReversalPrice : Condition to display the pivot price in the pivot label.
displayCumulativeVolume : Condition to display the cumulative volume for the pivot segment in the pivot label.
displayReversalPriceChange : Condition to display the change in price or percent from the previous pivot in the pivot label.
differencePriceMode : Reversal change display mode. Options are "Absolute" or "Percent".
draw : Condition to display lines and labels.
Point
A coordinate containing time and price information.
Fields:
tm : A value in UNIX time.
price : A value on the Y axis (price).
Pivot
A level of significance used to determine directional movement or potential support and resistance.
Fields:
ln : A line object connecting the `start` and `end` Point objects.
lb : A label object to display pivot values.
isHigh : A condition to determine if the pivot is a pivot high.
vol : Volume for the pivot segment.
start : The coordinate of the previous Point.
end : The coordinate of the current Point.
ZigZag
An object to maintain Zig Zag settings, pivots, and volume.
Fields:
settings : Settings object to provide calculation and display attributes.
pivots : An array of Pivot objects.
sumVol : The volume sum for the pivot segment.
extend : Pivot object used to project a line from the last pivot to the last bar.
█ FUNCTIONS
This library contains the following functions:
lastPivot(this)
Returns the last Pivot of `this` ZigZag if there is at least one Pivot to return, and `na` otherwise.
Parameters:
this : (series ZigZag) A ZigZag object.
Returns: (Pivot) The last Pivot in the ZigZag.
update(this)
Updates `this` ZigZag object with new pivots, volume, lines, labels.
Parameters:
this : (series ZigZag) a ZigZag object.
Returns: (bool) true if a new Zig Zag line is found or the last Zig Zag line has changed.
newInstance(settings)
Instantiates a new ZigZag object with `settings`. If no settings are provided, a default ZigZag object is created.
Parameters:
settings : (series Settings) A Settings object.
Returns: (ZigZag) A new ZigZag instance.
Intrabar Efficiency Ratio█ OVERVIEW
This indicator displays a directional variant of Perry Kaufman's Efficiency Ratio, designed to gauge the "efficiency" of intrabar price movement by comparing the sum of movements of the lower timeframe bars composing a chart bar with the respective bar's movement on an average basis.
█ CONCEPTS
Efficiency Ratio (ER)
Efficiency Ratio was first introduced by Perry Kaufman in his 1995 book, titled "Smarter Trading". It is the ratio of absolute price change to the sum of absolute changes on each bar over a period. This tells us how strong the period's trend is relative to the underlying noise. Simply put, it's a measure of price movement efficiency. This ratio is the modulator utilized in Kaufman's Adaptive Moving Average (KAMA), which is essentially an Exponential Moving Average (EMA) that adapts its responsiveness to movement efficiency.
ER's output is bounded between 0 and 1. A value of 0 indicates that the starting price equals the ending price for the period, which suggests that price movement was maximally inefficient. A value of 1 indicates that price had travelled no more than the distance between the starting price and the ending price for the period, which suggests that price movement was maximally efficient. A value between 0 and 1 indicates that price had travelled a distance greater than the distance between the starting price and the ending price for the period. In other words, some degree of noise was present which resulted in reduced efficiency over the period.
As an example, let's say that the price of an asset had moved from $15 to $14 by the end of a period, but the sum of absolute changes for each bar of data was $4. ER would be calculated like so:
ER = abs(14 - 15)/4 = 0.25
This suggests that the trend was only 25% efficient over the period, as the total distanced travelled by price was four times what was required to achieve the change over the period.
Intrabars
Intrabars are chart bars at a lower timeframe than the chart's. Each 1H chart bar of a 24x7 market will, for example, usually contain 60 intrabars at the LTF of 1min, provided there was market activity during each minute of the hour. Mining information from intrabars can be useful in that it offers traders visibility on the activity inside a chart bar.
Lower timeframes (LTFs)
A lower timeframe is a timeframe that is smaller than the chart's timeframe. This script determines which LTF to use by examining the chart's timeframe. The LTF determines how many intrabars are examined for each chart bar; the lower the timeframe, the more intrabars are analyzed, but fewer chart bars can display indicator information because there is a limit to the total number of intrabars that can be analyzed.
Intrabar precision
The precision of calculations increases with the number of intrabars analyzed for each chart bar. As there is a 100K limit to the number of intrabars that can be analyzed by a script, a trade-off occurs between the number of intrabars analyzed per chart bar and the chart bars for which calculations are possible.
Intrabar Efficiency Ratio (IER)
Intrabar Efficiency Ratio applies the concept of ER on an intrabar level. Rather than comparing the overall change to the sum of bar changes for the current chart's timeframe over a period, IER compares single bar changes for the current chart's timeframe to the sum of absolute intrabar changes, then applies smoothing to the result. This gives an indication of how efficient changes are on the current chart's timeframe for each bar of data relative to LTF bar changes on an average basis. Unlike the standard ER calculation, we've opted to preserve directional information by not taking the absolute value of overall change, thus allowing it to be utilized as a momentum oscillator. However, by taking the absolute value of this oscillator, it could potentially serve as a replacement for ER in the design of adaptive moving averages.
Since this indicator preserves directional information, IER can be regarded as similar to the Chande Momentum Oscillator (CMO) , which was presented in 1994 by Tushar Chande in "The New Technical Trader". Both CMO and ER essentially measure the same relationship between trend and noise. CMO simply differs in scale, and considers the direction of overall changes.
█ FEATURES
Display
Three different display types are included within the script:
• Line : Displays the middle length MA of the IER as a line .
Color for this display can be customized via the "Line" portion of the "Visuals" section in the script settings.
• Candles : Displays the non-smooth IER and two moving averages of different lengths as candles .
The `open` and `close` of the candle are the longest and shortest length MAs of the IER respectively.
The `high` and `low` of the candle are the max and min of the IER, longest length MA of the IER, and shortest length MA of the IER respectively.
Colors for this display can be customized via the "Candles" portion of the "Visuals" section in the script settings.
• Circles : Displays three MAs of the IER as circles .
The color of each plot depends on the percent rank of the respective MA over the previous 100 bars.
Different colors are triggered when ranks are below 10%, between 10% and 50%, between 50% and 90%, and above 90%.
Colors for this display can be customized via the "Circles" portion of the "Visuals" section in the script settings.
With either display type, an optional information box can be displayed. This box shows the LTF that the script is using, the average number of lower timeframe bars per chart bar, and the number of chart bars that contain LTF data.
Specifying intrabar precision
Ten options are included in the script to control the number of intrabars used per chart bar for calculations. The greater the number of intrabars per chart bar, the fewer chart bars can be analyzed.
The first five options allow users to specify the approximate amount of chart bars to be covered:
• Least Precise (Most chart bars) : Covers all chart bars by dividing the current timeframe by four.
This ensures the highest level of intrabar precision while achieving complete coverage for the dataset.
• Less Precise (Some chart bars) & More Precise (Less chart bars) : These options calculate a stepped LTF in relation to the current chart's timeframe.
• Very precise (2min intrabars) : Uses the second highest quantity of intrabars possible with the 2min LTF.
• Most precise (1min intrabars) : Uses the maximum quantity of intrabars possible with the 1min LTF.
The stepped lower timeframe for "Less Precise" and "More Precise" options is calculated from the current chart's timeframe as follows:
Chart Timeframe Lower Timeframe
Less Precise More Precise
< 1hr 1min 1min
< 1D 15min 1min
< 1W 2hr 30min
> 1W 1D 60min
The last five options allow users to specify an approximate fixed number of intrabars to analyze per chart bar. The available choices are 12, 24, 50, 100, and 250. The script will calculate the LTF which most closely approximates the specified number of intrabars per chart bar. Keep in mind that due to factors such as the length of a ticker's sessions and rounding of the LTF, it is not always possible to produce the exact number specified. However, the script will do its best to get as close to the value as possible.
Specifying MA type
Seven MA types are included in the script for different averaging effects:
• Simple
• Exponential
• Wilder (RMA)
• Weighted
• Volume-Weighted
• Arnaud Legoux with `offset` and `sigma` set to 0.85 and 6 respectively.
• Hull
Weighting
This script includes the option to weight IER values based on the percent rank of absolute price changes on the current chart's timeframe over a specified period, which can be enabled by checking the "Weigh using relative close changes" option in the script settings. This places reduced emphasis on IER values from smaller changes, which may help to reduce noise in the output.
█ FOR Pine Script™ CODERS
• This script imports the recently published lower_ltf library for calculating intrabar statistics and the optimal lower timeframe in relation to the current chart's timeframe.
• This script uses the recently released request.security_lower_tf() Pine Script™ function discussed in this blog post .
It works differently from the usual request.security() in that it can only be used on LTFs, and it returns an array containing one value per intrabar.
This makes it much easier for programmers to access intrabar information.
• This script implements a new recommended best practice for tables which works faster and reduces memory consumption.
Using this new method, tables are declared only once with var , as usual. Then, on the first bar only, we use table.cell() to populate the table.
Finally, table.set_*() functions are used to update attributes of table cells on the last bar of the dataset.
This greatly reduces the resources required to render tables.
Look first. Then leap.
[PX] External LevelHello everyone,
today I'd like to share a script, which enables you to use external logic to plot levels on your chart.
How does it work?
The concept is based on two scripts. One script, which uses an external input as a trigger to print a new level and one script that calculates an output, which will be fetched.
Sounds complicated? It really is not! Let's take a closer look.
// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// © paaax
//@version=4
study("RSI OS/OB")
l = input(14, "RSI Length")
ob = input(70, "Overbought")
os = input(30, "Oversold")
r = rsi(close, l)
hline(ob)
hline(os)
plot(r, "RSI", color=color.orange)
// The following plot produces an output, which will be fetched the "External Level"-script.
// It evaluates to one of the following three values: 1.0, -1.0 or 0.0
plot(crossover(r, ob) ? 1.0 : crossunder(r, os) ? -1.0 : 0.0, "Output", transp=100)
The example script above uses an RSI and two threshold levels (70 and 30). The logic here is, that whenever the RSI is crossing down the lower threshold or crossing up the upper threshold we'd consider the current movement to be either oversold or overbought. Therefore, it's a point of interest, which we could visualize with a level.
The script creates an output when the crossover or crossunder of a threshold happens. A crossover would result in a value of 1.0, a crossunder in a value of -1.0. In all other cases the value would be 0.0.
The output of the RSI script would then be used as an input of the External Level script, which has a "Source"-parameter in its input-section. If the fetched input shows 1.0, then the script prints a resistance level. If it shows -1.0 a support level will be printed. And that's basically it. A very simple approach to print levels on your chart with an infinite number of use cases.
For example, you could use fetch outputs from a MACD script, MA script, outputs based on volume or price movement. Just remember the output has to evaluate to either 1.0 or -1.0 and has to be selected in the input-section.
Hope that might be useful to some of you :)
Please click the "Like"-button and follow me for future open-source script publications.
If you are looking for help with your custom PineScript development, don't hesitate to contact me directly here on Tradingview or through the link in my signature :)
How to avoid repainting when NOT using security()Even when your code does not use security() calls, repainting dynamics still come into play in the realtime bar. Script coders and users must understand them and, if they choose to avoid repainting, need to know how to do so. This script demonstrates three methods to avoid repainting when NOT using the security() function.
Note that repainting dynamics when not using security() usually only come into play in the realtime bar, as historical data is fixed and thus cannot cause repainting, except in situations related to stock splits or dividend adjustments.
For those who don’t want to read
Configure your alerts to trigger “Once Per Bar Close” and you’re done.
For those who want to understand
Put this indicator on a 1 minute or seconds chart with a live symbol. As price changes you will see four of this script’s MAs (all except the two orange ones) move in the realtime bar. You are seeing repainting in action. When the current realtime bar closes and becomes a historical bar, the lines on the historical bars will no longer move, as the bar’s OHLC values are fixed. Note that you may need to refresh your chart to see the correct historical OHLC values, as exchange feeds sometimes produce very slight variations between the end values of the realtime bar and those of the same bar once it becomes a historical bar.
Some traders do not use signals generated by a script but simply want to avoid seeing the lines plotted by their scripts move during the realtime bar. They are concerned with repainting of the lines .
Other traders use their scripts to evaluate conditions, which they use to either plot markers on the chart, trigger alerts, or both. They may not care about the script’s plotted lines repainting, but do not want their markers to appear/disappear on the chart, nor their alerts to trigger for a condition that becomes true during the realtime bar but is no longer true once it closes. Those traders are more concerned with repainting of signals .
For each of the three methods shown in this script’s code, comments explain if its lines, markers and alerts will repaint or not. Through the Settings/Inputs you will be able to control plotting of lines and markers corresponding to each method, as well as experiment with the option, for method 2, of disabling only the lines plotting in the realtime bar while still allowing the markers and alerts to be generated.
An unavoidable fact is that non-repainting lines, markers or alerts are always late compared to repainting ones. The good news is that how late they are will in many cases be insignificant, so that the added reliability of the information they provide will largely offset the disadvantages of waiting.
Method 1 illustrates the usual way of going about things in a script. Its gray lines and markers will always repaint but repainting of the alerts the marker conditions generate can be avoided by configuring alerts to trigger “Once Per Bar Close”. Because this gray marker repaints, you will occasionally see it appear/disappear during the realtime bar when the gray MAs cross/un-cross.
Method 2 plots the same MAs as method 1, but in green. The difference is that it delays its marker condition by one bar to ensure it does not repaint. Its lines will normally repaint but its markers will not, as they pop up after the condition has been confirmed on the bar preceding the realtime bar. Its markers appear at the beginning of the realtime bar and will never disappear. When using this method alerts can be configured to trigger “Once Per Bar” so they fire the moment the marker appears on the chart at the beginning of the realtime bar. Note that the delay incurred between methods 1 and 2 is merely the instant between the close of a realtime bar and the beginning of the next one—a delay measured in milliseconds. Method 2 also allows its lines to be hidden in the realtime bar with the corresponding option in the script’s Settings/Inputs . This will be useful to those wishing to eliminate unreliable lines from the realtime bar. Commented lines in method 2 provide for a 2b option, which is to delay the calculation of the MAs rather than the cross condition. It has the obvious inconvenient of plotting delayed MAs, but may come in handy in some situations.
Method 3 is not the best solution when using MAs because it uses the open of bars rather than their close to calculate the MAs. While this provides a way of avoiding repainting, it is not ideal in the case of MA calcs but may come in handy in other cases. The orange lines and markers of method 3 will not repaint because the value of open cannot change in the realtime bar. Because its markers do not repaint, alerts may be configured using “Once Per Bar”.
Spend some time playing with the different options and looking at how this indicator’s lines plot and behave when you refresh you chart. We hope everything you need to understand and prevent repainting when not using security() is there.
Look first. Then leap.
Watchlist & Symbols Distribution [Daveatt]TLDR;
I got bored so I just coded the TradingView watchlist interface in Pinescript :)
TLDR 2:
Sharing it open-source what took me 1 full day to code - haven't coded in Pinescript in a long time, so I'm a bit slow for now :)
█ OVERVIEW
This script offers a comprehensive market analysis tool inspired by TradingView's native watchlist interface features.
It combines an interactive watchlist with powerful distribution visualization capabilities and a performance comparison panel.
The script was developed with a focus on providing multiple visualization methods while working within PineScript's limitations.
█ DEVELOPMENT BACKGROUND
The pie chart implementation was greatly inspired by the ( "Crypto Map Dashboard" script / )
adapting its circular visualization technique to create dynamic distribution charts. However, due to PineScript's 500-line limitation per script, I had to optimize the code to allow users to switch between pie chart analysis and performance comparison modes rather than displaying both simultaneously.
█ SETUP AND DISPLAY
For optimal visualization, users need to adjust the chart's display settings manually.
This involves:
Expanding the indicator window vertically to accommodate both the watchlist and graphical elements
Adjusting the Y-axis scale by dragging it to ensure proper spacing for the comparison panel grid
Modifying the X-axis scale to achieve the desired time window display
Fine-tuning these adjustments whenever switching between pie chart and comparison panel modes
These manual adjustments are necessary due to PineScript's limitations in controlling chart scaling programmatically. While this requires some initial setup, it allows users to customize the display to their preferred viewing proportions.
█ MAIN FEATURES
Distribution Analysis
The script provides three distinct distribution visualization modes through a pie chart.
Users can analyze their symbols by exchanges, asset types (such as Crypto, Forex, Futures), or market sectors.
If you can't see it well at first, adjust your chart scaling until it's displayed nicely.
Asset Exchanges
www.tradingview.com
Asset Types
Asset Sectors
The pie charts feature an optional 3D effect with adjustable depth and angle parameters. To enhance visual customization, four different color schemes are available: Default, Pastel, Dark, and Neon.
Each segment of the pie chart includes interactive tooltips that can be configured to show different levels of detail. Importantly, the pie chart only visualizes the distribution of selected assets (those marked with a checkmark in the watchlist), providing a focused view of the user's current interests.
Interactive Watchlist
The watchlist component displays real-time data for up to 10 user-defined symbols. Each entry shows current price, price changes (both absolute and percentage), volume metrics, and a comparison toggle.
The table is dynamically updated and features color-coded entries that correspond to their respective performance lines in the comparison chart. The watchlist serves as both an information display and a control panel for the comparison feature.
Performance Comparison
One of the script's most innovative features is its performance comparison panel.
Using polylines for smooth visualization, it tracks the 30-day performance of selected symbols relative to a 0% baseline.
The comparison chart includes a sophisticated grid system with 5% intervals and a dynamic legend showing current performance values.
The polyline implementation allows for fluid, continuous lines that accurately represent price movements, providing a more refined visual experience than traditional line plots. Like the pie charts, the comparison panel only displays performance lines for symbols that have been selected in the watchlist, allowing users to focus on their specific assets of interest.
█ TECHNICAL IMPLEMENTATION
The script utilizes several advanced PineScript features:
Dynamic array management for symbol tracking
Polyline-based charting for smooth performance visualization
Real-time data processing with security calls
Interactive tooltips and labels
Optimized drawing routines to maintain performance
Selective visualization based on user choices
█ CUSTOMIZATION
Users can personalize almost every aspect of the script:
Symbol selection and comparison preferences
Visual theme selection with four distinct color schemes
Pie chart dimensions and positioning
Tooltip information density
Component visibility toggles
█ LIMITATIONS
The primary limitation stems from PineScript's 500-line restriction per script.
This constraint necessitated the implementation of a mode-switching system between pie charts and the comparison panel, as displaying both simultaneously would exceed the line limit. Additionally, the script relies on manual chart scale adjustments, as PineScript doesn't provide direct control over chart scaling when overlay=false is enabled.
However, these limitations led to a more focused and efficient design approach that gives users control over their viewing experience.
█ CONCLUSION
All those tools exist in the native TradingView watchlist interface and they're better than what I just did.
However, now it exists in Pinescript... so I believe it's a win lol :)
Supertrend Alert with Arrows and Time FilterOverview
This script is designed to generate trading signals based on the Supertrend indicator, a popular technical analysis tool. The Supertrend indicator is used to identify the direction of the market trend and potential reversal points.
Supertrend Settings
The script uses two sets of Supertrend settings:
Small Supertrend
Factor: 3.0
ATR Period: 10
Big Supertrend
Factor: 10.0
ATR Period: 30
These settings are fixed and should not be altered to maintain the integrity of the signal generation process.
Configurable Parameters
startHour: The hour at which signal generation begins.
endHour: The hour at which signal generation ends.
These parameters allow users to focus on specific trading hours, optimizing the signal relevance to their trading strategy.
Signal Types
The script generates two types of signals:
Type 1: Reversal Signal
Long Signal: Triggered when the big Supertrend is in an uptrend, and the small Supertrend transitions from a downtrend to an uptrend.
Short Signal: Triggered when the big Supertrend is in a downtrend, and the small Supertrend transitions from an uptrend to a downtrend.
Type 2: Trend Change Signal
Long Signal: Triggered when the big Supertrend changes from a downtrend to an uptrend.
Short Signal: Triggered when the big Supertrend changes from an uptrend to a downtrend.
How the Script Works
Initialization: The script initializes with predefined Supertrend settings.
Data Input: Market data (e.g., price data) is fed into the script.
Supertrend Calculation: The script calculates the Supertrend values using the predefined factors and ATR periods.
Signal Detection: The script monitors the Supertrend values and detects the defined signals based on the conditions mentioned above.
Time Filtering: Signals are filtered based on the specified startHour and endHour, ensuring only relevant signals are displayed within the desired timeframe.
Usage
Set Parameters: Define startHour and endHour according to your trading schedule.
Run Script: Execute the script with market data input.
Interpret Signals: Monitor the generated signals and use them to inform your trading decisions.
Originality
Dual Supertrend Usage: The use of both a small and a big Supertrend to generate signals adds a layer of complexity and reliability to the signals.
Time-Based Filtering: Allows traders to focus on specific trading hours, enhancing the relevance and accuracy of signals.
Two Signal Types: The combination of reversal signals and trend change signals provides comprehensive market insights.
Conclusion
This Supertrend Signal Generator is a robust tool for traders seeking to leverage the Supertrend indicator for more informed trading decisions. By combining dual Supertrend settings and configurable trading hours, the script offers unique and flexible signal generation capabilities.
dashboard MTF,EMA User Guide: Dashboard MTF EMA
Script Installation:
Copy the script code.
Go to the script window (Pine Editor) on TradingView.
Paste the code into the script window.
Save the script.
Adding the Script to the Chart:
Return to your chart on TradingView.
Look for the script in the list of available scripts.
Add the script to the chart.
Interpreting the Table:
On the right side of the chart, you will see a table labeled "EMA" with arrows.
The rows correspond to different timeframes: 5 minutes (5M), 15 minutes (15M), 1 hour (1H), 4 hours (4H), and 1 day (1D).
Understanding the Arrows:
Each row of the table has two columns: "EMA" and an arrow.
"EMA" indicates the trend of the Exponential Moving Average (EMA) for the specified period.
The arrow indicates the direction of the trend: ▲ for bullish, ▼ for bearish.
Table Colors:
The colors of the table reflect the current trend based on the comparison between fast and slow EMAs.
Blue (▲) indicates a bullish trend.
Red (▼) indicates a bearish trend.
Table Theme:
The table has a dark (Dark) or light (Light) theme according to your preference.
The background, frame, and colors are adjusted based on the selected theme.
Usage:
Use the table as a quick indicator of trends on different timeframes.
The arrows help you quickly identify trends without navigating between different time units.
Designed to simplify analysis and avoid cluttering the chart with multiple indicators.
Pro Trading Art - Head And ShouldersHow the Script Works:
1. The script identifies potential Head and Shoulders patterns by searching for specific pivot highs and pivot lows in the price data.
2. It checks for the presence of a left shoulder, head, and right shoulder based on the conditions defined in the script.
3. If a valid Head and Shoulders pattern is found, the script plots lines and labels on the chart to visualize the pattern.
4. The script also identifies Inverted Head and Shoulders patterns using similar logic but with different conditions.
5. It plots lines and labels for the Inverted Head and Shoulders pattern.
6. The script generates short and long conditions based on the patterns. Short conditions trigger when the close price crosses below the neck level of a Head and Shoulders pattern, while long conditions trigger when the close price crosses above the neck level of an Inverted Head and Shoulders pattern.
7. It plots sell and buy signal shapes on the chart when the short and long conditions are met, respectively.
8. The script can also trigger alerts to notify the user when a valid Head and Shoulders or Inverted Head and Shoulders pattern is detected.
9. The script provides visual cues on the chart to help users identify potential trading opportunities.
10. The logic and parameters of the script can be modified by the user to customize the behavior and adapt it to different trading strategies.
How Users Can Make Profit Using This Script:
1. Identify potential short-selling opportunities: When a valid Head and Shoulders pattern is detected and a short condition is met, it indicates a potential trend reversal. Traders can consider opening short positions to profit from a downward price movement.
2. Identify potential long-buying opportunities: When a valid Inverted Head and Shoulders pattern is detected and a long condition is met, it suggests a potential trend reversal. Traders can consider opening long positions to profit from an upward price movement.
3. Combine with additional analysis: Users can utilize this script as a tool in their overall trading strategy. They can combine the signals generated by the script with other technical indicators, fundamental analysis, or market sentiment to make more informed trading decisions.
4. Define appropriate entry and exit points: Traders can use the lines and labels plotted by the script to determine entry and exit points for their trades. For example, they may choose to enter a short position after the price crosses below the neck level and exit when the price reaches a predetermined target or when the pattern is invalidated.
5. Set risk management measures: It is important for users to implement proper risk management strategies when trading based on the script's signals. They should define stop-loss orders to limit potential losses if the trade goes against them and consider setting profit targets to secure profits when the trade moves in their favor.
Tick travel ⍗This script is a further exploration of 'ticks' (only on realtime - live bars), based on my previous script:
- www.tradingview.com -
What are 'ticks'?
... Once the script’s execution reaches the rightmost bar in the dataset, if trading is currently active on the chart’s symbol,
then Pine indicators will execute once every time an update occurs, i.e., price or volume changes ...
(www.tradingview.com)
This script has 2 parts:
1) Option: ' Tick up/down'
This is a further progression of previous work.
During bar development, every time there is an update (tick), a dot is placed.
If for example there is 1 tick (first of new bar), a dot will be placed on 1,
if it is the 8th tick off that bar, there will be a dot placed on 8.
While my previous script had the issue that there was an upper limit per bar (max 32),
this script (because it is working with labels) can place max 500 dots.
For each bar this is better, it has to be mentioned though that looking in history, once the limit of 500 has been reached,
you'll notice the last ones are being deleted. This is one of the reasons the script is not suitable for higher timeframes
(1h and higher, even higher than 5 minutes can give some issues if it is a highly traded ticker), if a bar would have more
than 500 ticks, they won't be drawn anymore (which is not desirable of course)
2) Option: ' Tick progression'
These are the same ticks, but placed on the candle itself, or you can show the candle:
Or 'without' candle (or 'black' colour):
When 'No candles' are enabled, the 'candles' get the colour at the right.
At the moment it is not possible to drawn between 2 candles, this technique uses labels with 'text',
each tick on a candle will have a 'space' added, so you can see a progression to the right.
Colours
- if price is higher than previous tick price -> green
- if price is lower than previous tick price -> red
- otherwise -> blue (dimmed)
There are options to choose the 'dot', when choosing 'custom',
just enter (copy/paste) your symbol of your choice in the 'custom' field:
Caveats:
- Labels and text will not always be exactly on the price itself
- The scripts needs more testings, possibly some ticks don't always get drawn as they should.
The lower the timeframe, the more possible issues can occur
- Since (candle option) the dots move to the right, the higher the timeframe and/or the more ticks,
the sooner ticks will go in the area of next candle.
That's why I made a separate 'start symbol'
-> This is the very first tick on each candle, then you can zoom in/out more easily until the dots don't merge into each other candle area:
A timeframe higher than 5 minutes mostly won't be feasible I believe
This script wouldn't be possible without the help of @LucF, also because of his script
With very much respect I am hugely inspired by him! Many Thanks to him, Tradingview, and everything associated with them!
Cheers!
Matrix Library (Linear Algebra, incl Multiple Linear Regression)What's this all about?
Ever since 1D arrays were added to Pine Script, many wonderful new opportunities have opened up. There has been a few implementations of matrices and matrix math (most notably by TradingView-user tbiktag in his recent Moving Regression script: ). However, so far, no comprehensive libraries for matrix math and linear algebra has been developed. This script aims to change that.
I'm not math expert, but I like learning new things, so I took it upon myself to relearn linear algebra these past few months, and create a matrix math library for Pine Script. The goal with the library was to make a comprehensive collection of functions that can be used to perform as many of the standard operations on matrices as possible, and to implement functions to solve systems of linear equations. The library implements matrices using arrays, and many standard functions to manipulate these matrices have been added as well.
The main purpose of the library is to give users the ability to solve systems of linear equations (useful for Multiple Linear Regression with K number of independent variables for example), but it can also be used to simulate 2D arrays for any purpose.
So how do I use this thing?
Personally, what I do with my private Pine Script libraries is I keep them stored as text-files in a Libraries folder, and I copy and paste them into my code when I need them. This library is quite large, so I have made sure to use brackets in comments to easily hide any part of the code. This helps with big libraries like this one.
The parts of this script that you need to copy are labeled "MathLib", "ArrayLib", and "MatrixLib". The matrix library is dependent on the functions from these other two libraries, but they are stripped down to only include the functions used by the MatrixLib library.
When you have the code in your script (pasted somewhere below the "study()" call), you can create a matrix by calling one of the constructor functions. All functions in this library start with "matrix_", and all constructors start with either "create" or "copy". I suggest you read through the code though. The functions have very descriptive names, and a short description of what each function does is included in a header comment directly above it. The functions generally come in the following order:
Constructors: These are used to create matrices (empy with no rows or columns, set shape filled with 0s, from a time series or an array, and so on).
Getters and setters: These are used to get data from a matrix (like the value of an element or a full row or column).
Matrix manipulations: These functions manipulate the matrix in some way (for example, functions to append columns or rows to a matrix).
Matrix operations: These are the matrix operations. They include things like basic math operations for two indices, to transposing a matrix.
Decompositions and solvers: Next up are functions to solve systems of linear equations. These include LU and QR decomposition and solvers, and functions for calculating the pseudo-inverse or inverse of a matrix.
Multiple Linear Regression: Lastly, we find an implementation of a multiple linear regression, including all the standard statistics one can expect to find in most statistical software packages.
Are there any working examples of how to use the library?
Yes, at the very end of the script, there is an example that plots the predictions from a multiple linear regression with two independent (explanatory) X variables, regressing the chart data (the Y variable) on these X variables. You can look at this code to see a real-world example of how to use the code in this library.
Are there any limitations?
There are no hard limiations, but the matrices uses arrays, so the number of elements can never exceed the number of elements supported by Pine Script (minus 2, since two elements are used internally by the library to store row and column count). Some of the operations do use a lot of resources though, and as a result, some things can not be done without timing out. This can vary from time to time as well, as this is primarily dependent on the available resources from the Pine Script servers. For instance, the multiple linear regression cannot be used with a lookback window above 10 or 12 most of the time, if the statistics are reported. If no statistics are reported (and therefore not calculated), the lookback window can usually be extended to around 60-80 bars before the servers time out the execution.
Hopefully the dev-team at TradingView sees this script and find ways to implement this functionality diretly into Pine Script, as that would speed up many of the operations and make things like MLR (multiple linear regression) possible on a bigger lookback window.
Some parting words
This library has taken a few months to write, and I have taken all the steps I can think of to test it for bugs. Some may have slipped through anyway, so please let me know if you find any, and I'll try my best to fix them when I have time to do so. This library is intended to help the community. Therefore, I am releasing the library as open source, in the hopes that people may improving on it, or using it in their own work. If you do make something cool with this, or if you find ways to improve the code, please let me know in the comments.
EMA TrendThe purpose of this script is to identify price trends based on EMAs. The relative position of price to specific EMAs and the position of certain EMAs towards each other are used to determine the trend direction. The script is intended for investors as a tool to define a basis for further evaluation. I do not use the script as a signal generator and would not recommend doing so without the help of additional indicators.
How to work with the script
The major (or long term) trend direction is determined by the 144 EMA much in the same way as the 200 MA is used in other systems. If the price is above the 144 EMA we are in a long term uptrend, below we are in a long term downtrend. This is to be taken with a grain of salt though. The 144 EMA is considerably shorter than the 200 SMA and is more prone to the price fluctuating around it during periods without a strong long term trend. I recommend using this as a confirmation for the short term trend.
The short term trend is derived from the position and slope of the price, the 21 EMA and the 55 EMA. If the price is above the 21 EMA, the 21 above the 55 EMA, both EMAs are sloping upwards and the distance between the two is increasing, we are talking about an uptrend (and vice versa for a downtrend). This is visualized by the color of the fill between the 144 EMA and close price. Green for uptrend, red for downtrend and no color for an undetermined trend.
The EMAs used are: 21 , 34 , 55 , 89 , 144 , 233 . Most of the EMAs are at 50 transparency to appear less dominant. For orientation, the 144 EMA is bright green to indicate its general importance for the trend determination, and the 55 EMAs is not transparent mainly to be able to identify positioning when the EMAs are close together.
Base time frame EMA
The 144 EMA is plotted twice where one is fixed to the daily time frame (can be configured) to be able to have the 144 on different timeframes during analysis. I find this very useful to keep the focus on my main time frame while analyzing trend on lower or higher time frames. This can also be turned off.
Configurability
This script is less configurable than I generally like with my other scripts. The reason is that the title attribute of the plots is not dynamic, and I use the data window often to get exact values from the script to determine buy targets for pullbacks and other things. Hence, I prefer not to have random names (or no names) in there to save mental capacity. If this ever becomes available, I'll gladly add this to this script. Till then, I encourage you to take the script and adjust it to your own needs. It should be simple enough even if you are just starting out in pine.
Business Cycle Indicators (Normalized)This script aggregates and normalizes several key economic indicators to provide a comprehensive view of the business cycle and overall market conditions. By combining these indicators into a single, normalized average line, the script helps identify overarching trends and shifts in the economy, aiding in more informed trading and investment decisions.
Included Indicators:
Inverted National Financial Conditions Index (NFCI):
Symbol: FRED:NFCI
Measures financial stress in the markets. An inverted NFCI aligns higher values with positive financial conditions.
Inverted Net Percentage of Banks Tightening Lending Standards (DRTSCIS):
Symbol: FRED:DRTSCIS
Reflects changes in bank lending practices. Inverting this indicator means higher values indicate easing lending standards, which is generally positive for economic growth.
HYG Close Price (iShares High Yield Corporate Bond ETF):
Symbol: AMEX:HYG
Represents the performance of high-yield corporate bonds, providing insight into credit market conditions.
Inverted High-Yield Credit Spread (BAMLH0A0HYM2):
Symbol: FRED:BAMLH0A0HYM2
Measures the spread between high-yield bonds and risk-free securities. A narrower (inverted) spread indicates better market conditions.
Manufacturing/Non-Manufacturing New Orders Ratio:
Symbols: ECONOMICS:USMNO (Manufacturing), ECONOMICS:USNMNO (Non-Manufacturing)
Compares manufacturing to non-manufacturing new orders to gauge shifts in economic activity.
US PMI (Purchasing Managers' Index):
Symbol: ECONOMICS:USBCOI
An indicator of the economic health of the manufacturing sector.
10-Year Inflation Breakeven (T10YIE):
Symbol: FRED:T10YIE
Represents market expectations of inflation over the next ten years.
Inverted 10-Year Real Yield (DFII10):
Symbol: FRED:DFII10
Reflects the real yield on 10-year Treasury Inflation-Protected Securities (TIPS). Inverted to align higher values with positive economic sentiment.
Copper/Gold Ratio:
Symbols: CAPITALCOM:COPPER (Copper), TVC:GOLD (Gold)
Compares the prices of copper and gold, often used as a barometer for global economic activity.
Features:
Normalized Indicators: Each indicator is normalized to a 0-100 scale to facilitate direct comparison, regardless of their original units or scales.
Normalized Average Line: Calculates and plots the average of all available normalized indicators, providing a single line that represents the combined economic signals.
Customizable Display:
Show Individual Indicators: Option to display individual normalized indicators for detailed analysis.
Show Normalized Average Line: Option to display the normalized average line for a consolidated view.
Dynamic Labeling: Displays the latest value of the normalized average directly on the chart for quick reference.
How to Use:
Adding the Script:
Apply the script to a chart in TradingView using a timeframe that aligns with the frequency of the economic data (daily or weekly recommended).
Customization:
Show Normalized Average Line: Enabled by default to display the combined indicator.
Show Individual Indicators: Enable this option in the script settings to display all individual normalized indicators.
Interpretation:
Normalized Scale (0-100): Higher values generally indicate stronger economic conditions, while lower values may suggest weakening conditions.
Trend Analysis: Use the normalized average line to identify trends and potential turning points in the business cycle.
Notes:
Data Availability: Ensure you have access to all the data sources used in the script. Some data feeds may require specific TradingView subscriptions.
Indicator Limitations: Economic indicators are subject to revisions and may not reflect real-time market conditions.
No Investment Advice: This script is a tool for analysis and should not be considered as financial advice. Always conduct your own research before making investment decisions.
[SGM GARCH Volatility]I'm excited to share with you a Pine Script™ that I developed to analyze GARCH (Generalized Autoregressive Conditional Heteroskedasticity) volatility. This script allows you to calculate and plot GARCH volatility on TradingView. Let's see together how it works!
Introduction
Volatility is a key concept in finance that measures the variation in prices of a financial asset. The GARCH model is a statistical method that predicts future volatility based on past volatilities and prediction residuals (errors).
Indicator settings
We define several parameters for our indicator:
length = input.int(20, title="Length")
p = input.int(1, title="Lag order (p)")
q = input.int(1, title="Degree of moving average (q)")
cluster_value = input(0.2,title="cluster value")
length: The period used for the calculations, default 20.
p: The order of the delay for the GARCH model.
q: The degree of the moving average for the GARCH model.
cluster_value: A threshold value used to color the graph.
Calculation of logarithmic returns
We calculate logarithmic returns to capture price changes:
logReturns = math.log(close) - math.log(close )
Initializing arrays
We initialize arrays to store residuals and volatilities:
var float residuals = array.new_float(length, 0)
var float volatilities = array.new_float(length, 0)
We add the new logarithmic returns to the tables and keep their size constant:
array.unshift(residuals, logReturns)
if (array.size(residuals) > length)
array.pop(residuals)
We then calculate the mean and variance of the residuals:
meanResidual = array.avg(residuals)
varianceResidual = array.stdev(residuals, meanResidual)
volatility = math.sqrt(varianceResidual)
We update the volatility table with the new value:
array.unshift(volatilities, volatility)
if (array.size(volatilities) > length)
array.pop(volatilities)
GARCH volatility is calculated from accumulated data:
var float garchVolatility = na
if (array.size(volatilities) >= length and array.size(residuals) >= length)
alpha = 0.1 // Alpha coefficient
beta = 0.85 // Beta coefficient
omega = 0.01 // Omega constant
sumVolatility = 0.0
for i = 0 to p-1
sumVolatility := sumVolatility + beta * math.pow(array.get(volatilities, i), 2)
sumResiduals = 0.0
for j = 0 to q-1
sumResiduals := sumResiduals + alpha * math.pow(array.get(residuals, j), 2)
garchVolatility := math.sqrt(omega + sumVolatility + sumResiduals)
Plot GARCH volatility
We finally plot the GARCH volatility on the chart and add horizontal lines for easier visual analysis:
plt = plot(garchVolatility, title="GARCH Volatility", color=color.rgb(33, 149, 243, 100))
h1 = hline(0.1)
h2 = plot(cluster_value)
h3 = hline(0.3)
colorGarch = garchVolatility > cluster_value ? color.red: color.green
fill(plt, h2, color = colorGarch)
colorGarch: Determines the fill color based on the comparison between garchVolatility and cluster_value.
Using the script in your trading
Incorporating this Pine Script™ into your trading strategy can provide you with a better understanding of market volatility and help you make more informed decisions. Here are some ways to use this script:
Identification of periods of high volatility:
When the GARCH volatility is greater than the cluster value (cluster_value), it indicates a period of high volatility. Traders can use this information to avoid taking large positions or to adjust their risk management strategies.
Anticipation of price movements:
An increase in volatility can often precede significant price movements. By monitoring GARCH volatility spikes, traders can prepare for potential market reversals or accelerations.
Optimization of entry and exit points:
By using GARCH volatility, traders can better identify favorable times to enter or exit a position. For example, entering a position when volatility begins to decrease after a peak can be an effective strategy.
Adjustment of stops and objectives:
Since volatility is an indicator of the magnitude of price fluctuations, traders can adjust their stop-loss and take-profit orders accordingly. Periods of high volatility may require wider stops to avoid being exited from a position prematurely.
That's it for the detailed explanation of this Pine Script™ script. Don’t hesitate to use it, adapt it to your needs and share your feedback! Happy analysis and trading everyone!
High Volume AlertThe High Volume Alert Script is developed for all traders focusing on volume analysis in their trading strategies, providing alerts for unusually high trading volumes during specified trading sessions.
Functionality:
Volume Moving Average Calculation:
Average Volume = Moving Average(Volume) = Sum of last the x last candles Volume
Where n is the user-defined period for the moving average calculation (denoted as movingaverageinput in the script. This moving average serves as the baseline to compare current volume levels against historical averages.
High Volume Detection:
HighVolume = CurrentVolume >= (MA(Volume) x HighVolumeRatio)
Here, HighVolumeRatio is a user-defined multiplier that sets the threshold for what is considered high volume. If the current volume exceeds this threshold (the product of the moving average of volume and the HighVolumeRatio ), the script identifies this as a high-volume event.
Session Filtering:
The script further refines these alerts by ensuring they only trigger during the specified trading session, enhancing relevance for traders interested in specific market hours. This session is defined by the sess and timezone parameters.
Visualisation and Alerts:
If high volume is detected (HighVolume = True), the script colors the volume bar with the highVolumeColor . If the option is selected, it also changes the color of the candlestick to either highVolumeCandleColorUp (for bullish candles) or highVolumeCandleColorDown (for bearish candles), depending on the price movement within the high-volume period. An alert is generated through the alertcondition function when high volume is detected during the specified session, notifying the trader of potentially significant market activity.
Application in Trading:
This indicator serves traders who prioritize volume as a leading indicator of potential price movement. High trading volumes may indicate the presence of significant market activity, often associated with events like news releases, market openings, or large trades, which can precede price movements.
Originality and Practicality:
This script is self-developed, aiming to fill the gap in automatic ratio adjusted volume alerts within the TradingView environment.
Conclusion:
The High Volume Alert Script is an essential tool for traders who integrate volume analysis into their strategy, offering tailored alerts and visual cues for high volume periods.
Compliance and Limitations:
The script complies with TradingView scripting standards, ensuring no lookahead bias and maintaining real-time data integrity. However, its utility depends on the availability on volume data, and please be aware that forex pairs never offer real volume data, this tool is best used with a exchange traded symbol.
Bond Yield SpreadThe Bond Yield Spread Script is developed for forex traders, offering an automated tool to calculate the bond yield spread between two countries associated with the forex pair displayed on the chart.
Functionality:
The script starts by identifying the base and quote currencies of the current forex pair and aligns them with their corresponding national bond symbols based on user-selected maturity, with options ranging from 01Y to 30Y. It calculates the yield spread by subtracting the bond yield associated with the quote country from that of the base country, following the formula:
Yield Spread = Yield(Base Country) − Yield(Quote Country)
which is then displayed as a plot line on the chart.
This script relies solely on TradingView's internal yield symbols, with the following calculation:
"currency" => "first two letters" + maturity
And maturity, in this case, is the value that is configured in the indicator settings, for example:
"EUR" => "EU" + "02Y" will result in EU02Y -> which will be used in the formula, depending on the quote or base currency.
Application in Trading:
This indicator is invaluable for traders employing carry trading strategies or assessing currency strength based on traded interest rates as an indicator. A higher yield spread typically indicates a stronger currency, because the return obtained for holding the currency is higher.
Originality and Practicality:
This script is self-developed, aiming to fill the gap in automatic bond yield comparisons within the TradingView environment. It is particularly beneficial for traders focusing on macroeconomic factors affecting forex markets. Unlike other scripts, it integrates various bond maturities into one tool, enhancing its utility and application range.
Conclusion:
Designed for traders incorporating macroeconomics in their strategy, this script will be useful to calculate the bond yield differences automatically without having to enter a new formula for every new currency pair.
Compliance and Limitations:
The script complies with TradingView scripting standards, ensuring no lookahead bias and maintaining real-time data integrity. However, its utility depends on the comprehensive availability of bond yield data within TradingView. As not all countries issue bonds for each listed maturity, this may limit the script’s application for certain currency pairs or specific maturities.
Сoncentrated Market Maker Strategy by oxowlConcentrated Market Maker Strategy by oxowl. This script plots an upper and lower bound for liquidity provision, and checks for rebalancing conditions. It also includes alert conditions for when the price crosses the upper or lower bounds.
Here's an overview of the script:
It defines the input parameters: liquidity range percentage, rebalance frequency in minutes, and minimum trade size in assets.
It calculates the upper and lower bounds for liquidity provision based on the liquidity range percentage.
It initializes variables for the last rebalance time and price.
It defines a rebalance condition based on the frequency and current price within the specified range.
If the rebalance condition is met, it updates the last rebalance time and price.
It plots the upper and lower bounds on the chart as lines and adds price labels for both bounds.
It defines alert conditions for when the price crosses the upper or lower bounds.
Finally, it creates alert conditions with appropriate messages for when the price crosses the upper or lower bounds.
Concentrated liquidity is a concept often used in decentralized finance (DeFi) market-making strategies. It allows liquidity providers (LPs) to focus their liquidity within a specific price range, rather than across the entire price curve. Using an indicator with concentrated liquidity can offer several advantages:
Increased capital efficiency: Concentrated liquidity allows LPs to allocate their capital within a narrower price range. This means that the same amount of capital can generate more significant price impact and potentially higher returns compared to providing liquidity across a broader range.
Customized risk exposure: LPs can choose the price range they feel most comfortable with, allowing them to better manage their risk exposure. By selecting a range based on their market outlook, they can optimize their positions to maximize potential returns.
Adaptive strategies: Indicators that support concentrated liquidity can help traders adapt their strategies based on market conditions. For example, they can choose to provide liquidity around a stable price range during low-volatility periods or adjust their range when market conditions change.
To continue integrating this script into your trading strategy, follow these steps:
Import the script into your TradingView account. Navigate to the Pine editor, paste the code, and save it as a new script.
Apply the indicator to a trading pair chart. You can customize the input parameters (liquidity range percentage, rebalance frequency, and minimum trade size) based on your preferences and risk tolerance.
Set alerts for when the price crosses the upper or lower bounds. This will notify you when it's time to take action, such as adding or removing liquidity, or rebalancing your position.
Monitor the performance of your strategy over time. Adjust the input parameters as needed to optimize your returns and manage risk effectively.
(Optional) Integrate the script with a trading bot or automation platform. If you're using an API-based trading solution, you can incorporate the logic and conditions from the script into your bot's algorithm to automate the process of providing concentrated liquidity and rebalancing your positions.
Remember that no strategy is foolproof, and past performance is not indicative of future results. Always exercise caution when trading and carefully consider your risk tolerance.
Strategy BackTest Display Statistics - TraderHalaiThis script was born out of my quest to be able to display strategy back test statistics on charts to allow for easier backtesting on devices that do not natively support backtest engine (such as mobile phones, when I am backtesting from away from my computer). There are already a few good ones on TradingView, but most / many are too complicated for my needs.
Found an excellent display backtest engine by 'The Art of Trading'. This script is a snippet of his hard work, with some very minor tweaks and changes. Much respect to the original author.
Full credit to the original author of this script. It can be found here: www.tradingview.com
I decided to modify the script by simplifying it down and make it easier to integrate into existing strategies, using simple copy and paste, by relying on existing tradingview strategy backtester inputs. I have also added 3 additional performance metrics:
- Max Run Up
- Average Win per trade
- Average Loss per trade
As this is a work in progress, I will look to add in more performance metrics in future, as I further develop this script.
Feel free to use this display panel in your scripts and strategies.
Thanks and enjoy :)
logLibrary "log"
Logging library for easily displaying debug, info, warn, error and critical messages.
No real need to explain why you might want to use this library! I'm sure you've all experienced the frustration of trying to understand the data state of your scripts... so, enjoy! More on it's way...
(Don't forget to check the helpers in the script and the useful tips below)
Some Useful Tips
By default the log console persists between bars (for history) and bars and ticks (for realtime).
Sometimes it is useful to clear the log after each candle or tick (assuming we are using the above helpers):
```
log_print(clear = true) // starts afresh on every bar and tick (excludes historical bars but good realtime tick analysis)
log_print(clear = barstate.isnew) // clears the log at the start of each bar (again, excludes historical but good realtime candle analysis)
```
It is also useful to be able to selectively understand the state of data at specific points or times within a script:
```
if log.once()
debug('useful variable', my_var) // this log only gets written once, upon first execution of this statement
if log.only(5)
debug3(a, b, c) // these variables are only logged the first five times this statement is executed
log_print(clear = false) // clear must be false and you should not write other logs on every bar, or the above will be lost
```
Final tip. If you want to view ONLY log entries of a particular level, then negate the constant:
```
log_print(level = -LOG_DEBUG)
```
Detailed Interface
once() Restrict execution to only happen once. Usage: if assert.once()\n happens_once()
Returns: bool, true on first execution within scope, false subsequently
only(repeat) Restrict execution to happen a set number of times. Usage: if assert.only(5)\n happens_five_times()
Parameters:
repeat : int, the number of times to return true
Returns: bool, true for the set number of times within scope, false subsequently
init() Initialises the log array
Returns: string , tuple based array to contain all pending log entries (__LOG)
clear(msgs) Clears the log array
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
trace(msgs, msg) Writes a trace message to the log console
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
msg : string, the trace message to write to the log
debug(msgs, msg) Writes a debug message to the log console
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
msg : string, the debug message to write to the log
info(msgs, msg) Writes an info message to the log console
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
msg : string, the info message to write to the log
warn(msgs, msg) Writes a warning message to the log console
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
msg : string, the warn message to write to the log
error(msgs, msg) Writes an error message to the log console
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
msg : string, the error message to write to the log
fatal(msgs, msg) Writes a critical message to the log console
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
msg : string, the fatal message to write to the log
log(msgs, level, msg) Write a log message to the log console with a custom level
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
level : ing, the logging level to assign to the message
msg : string, the log message to write to the log
severity(msgs) Checks the unprocessed log messages and returns the highest present level
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
Returns: int, the highest level found within the unfiltered logs
print(msgs, level, clear, rows, text_size, position) Prints all log messages to the screen
Parameters:
msgs : string , the current collection of unfiltered and unprocessed logs (__LOG)
level : int, the minimum required log level of each message to be displayed
clear : bool, clear the printed log console after each render (useful with realtime when set to barstate.isconfirmed)
rows : int, the number of rows to display in the log console
text_size : string, the text size of the log console (global size vars)
position : string, the position of the log console (global position vars)
unittest_log(case) Log module unit tests, for inclusion in parent script test suite. Usage: log.unittest_log(__ASSERTS)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
unittest(verbose) Run the log module unit tests as a stand alone. Usage: log.unittest()
Parameters:
verbose : bool, optionally disable the full report to only display failures
assertLibrary "assert"
Production ready assertions and auto-reporting for unit testing pine scripts.
This library was born from the need to maintain production level stability and catch regressions / bugs early and fast. I hope this help you trust your pine scripts too. More libraries and tools on their way... please follow for more.
Please see the script for helpers to copy into your own scripts as well as examples at the bottom of the library unit testing itself.
Quick Reference
```
case = assert.init()
new_case(case, 'Asserts for floats and ints')
assert.equal(a, b, case, 'a == b')
assert.not_equal(a, b, case, 'a != b')
assert.nan(a, case, 'a == na')
assert.not_nan(a, case, 'a != na')
assert.is_in(a, b, case, 'a in b ')
assert.is_not_in(a, b, case, 'a not in b ')
assert.array_equal(a, b, case, 'a == b ')
new_case(case, 'Asserts for ints only')
assert.int_in(a, b, case, 'a in b ')
assert.int_not_in(a, b, case, 'a not in b ')
assert.int_array_equal(a, b, case, 'a == b ')
new_case(case, 'Asserts for bools only')
assert.is_true(a, case, 'a == true')
assert.is_false(a, case, 'a == false')
assert.bool_equal(a, b, case, 'a == b')
assert.bool_not_equal(a, b, case, 'a != b')
assert.bool_nan(a, case, 'a == na')
assert.bool_not_nan(a, case, 'a != na')
assert.bool_array_equal(a, b, case, 'a == b ')
new_case(case, 'Asserts for strings only')
assert.str_equal(a, b, case, 'a == b')
assert.str_not_equal(a, b, case, 'a != b')
assert.str_nan(a, case, 'a == na')
assert.str_not_nan(a, case, 'a != na')
assert.str_in(a, b, case, 'a in b ')
assert.str_not_in(a, b, case, 'a not in b ')
assert.str_array_equal(a, b, case, 'a == b ')
assert.report(case)
```
Detailed Interface
once() Restrict execution to only happen once. Usage: if assert.once()\n happens_once()
Returns: bool, true on first execution within scope, false subsequently
init() Initialises the asserts array
Returns: string , tuple based array containing all unit test results and current case details (__ASSERTS)
equal(a, b, case, name) Numeric assert equal. Usage: assert.equal(1, 1, case, 'one == one')
Parameters:
a : float, numeric value "a" to compare equal to "b"
b : float, numeric value "b" to compare equal to "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
not_equal(a, b, case, name) Numeric assert not equal. Usage: assert.not_equal(1, 2, case, 'one != two')
Parameters:
a : float, numeric value "a" to compare not equal "b"
b : float, numeric value "b" to compare not equal "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
nan(a, case, name) Numeric assert is NaN. Usage: assert.nan(float(na), case, 'number is NaN')
Parameters:
a : float, numeric value "a" to check is NaN
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
not_nan(a, case, name) Numeric assert is not NaN. Usage: assert.not_nan(1, case, 'number is not NaN')
Parameters:
a : float, numeric value "a" to check is not NaN
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
is_in(a, b, case, name) Numeric assert value in float array. Usage: assert.is_in(1, array.from(1.0), case, '1 is in ')
Parameters:
a : float, numeric value "a" to check is in array "b"
b : float , array "b" to check contains "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
is_not_in(a, b, case, name) Numeric assert value not in float array. Usage: assert.is_not_in(2, array.from(1.0), case, '2 is not in ')
Parameters:
a : float, numeric value "a" to check is not in array "b"
b : float , array "b" to check does not contain "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
array_equal(a, b, case, name) Float assert arrays are equal. Usage: assert.array_equal(array.from(1.0), array.from(1.0), case, ' == ')
Parameters:
a : float , array "a" to check is identical to array "b"
b : float , array "b" to check is identical to array "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
int_in(a, b, case, name) Integer assert value in integer array. Usage: assert.int_in(1, array.from(1), case, '1 is in ')
Parameters:
a : int, value "a" to check is in array "b"
b : int , array "b" to check contains "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
int_not_in(a, b, case, name) Integer assert value not in integer array. Usage: assert.int_not_in(2, array.from(1), case, '2 is not in ')
Parameters:
a : int, value "a" to check is not in array "b"
b : int , array "b" to check does not contain "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
int_array_equal(a, b, case, name) Integer assert arrays are equal. Usage: assert.int_array_equal(array.from(1), array.from(1), case, ' == ')
Parameters:
a : int , array "a" to check is identical to array "b"
b : int , array "b" to check is identical to array "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
is_true(a, case, name) Boolean assert is true. Usage: assert.is_true(true, case, 'is true')
Parameters:
a : bool, value "a" to check is true
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
is_false(a, case, name) Boolean assert is false. Usage: assert.is_false(false, case, 'is false')
Parameters:
a : bool, value "a" to check is false
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
bool_equal(a, b, case, name) Boolean assert equal. Usage: assert.bool_equal(true, true, case, 'true == true')
Parameters:
a : bool, value "a" to compare equal to "b"
b : bool, value "b" to compare equal to "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
bool_not_equal(a, b, case, name) Boolean assert not equal. Usage: assert.bool_not_equal(true, false, case, 'true != false')
Parameters:
a : bool, value "a" to compare not equal "b"
b : bool, value "b" to compare not equal "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
bool_nan(a, case, name) Boolean assert is NaN. Usage: assert.bool_nan(bool(na), case, 'bool is NaN')
Parameters:
a : bool, value "a" to check is NaN
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
bool_not_nan(a, case, name) Boolean assert is not NaN. Usage: assert.bool_not_nan(true, case, 'bool is not NaN')
Parameters:
a : bool, value "a" to check is not NaN
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
bool_array_equal(a, b, case, name) Boolean assert arrays are equal. Usage: assert.bool_array_equal(array.from(true), array.from(true), case, ' == ')
Parameters:
a : bool , array "a" to check is identical to array "b"
b : bool , array "b" to check is identical to array "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_equal(a, b, case, name) String assert equal. Usage: assert.str_equal('hi', 'hi', case, '"hi" == "hi"')
Parameters:
a : string, value "a" to compare equal to "b"
b : string, value "b" to compare equal to "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_not_equal(a, b, case, name) String assert not equal. Usage: assert.str_not_equal('hi', 'bye', case, '"hi" != "bye"')
Parameters:
a : string, value "a" to compare not equal "b"
b : string, value "b" to compare not equal "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_nan(a, case, name) String assert is NaN. Usage: assert.str_nan(string(na), case, 'string is NaN')
Parameters:
a : string, value "a" to check is NaN
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_not_nan(a, case, name) String assert is not NaN. Usage: assert.str_not_nan('hi', case', 'string is not NaN')
Parameters:
a : string, value "a" to check is not NaN
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_in(a, b, case, name) String assert value in string array. Usage: assert.str_in('hi', array.from('hi'), case, '"hi" in ')
Parameters:
a : string, value "a" to check is in array "b"
b : string , array "b" to check contains "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_not_in(a, b, case, name) String assert value not in string array. Usage: assert.str_in('hi', array.from('bye'), case, '"hi" in ')
Parameters:
a : string, value "a" to check is not in array "b"
b : string , array "b" to check does not contain "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
str_array_equal(a, b, case, name) String assert arrays are equal. Usage: assert.str_array_equal(array.from('hi'), array.from('hi'), case, ' == ')
Parameters:
a : string , array "a" to check is identical to array "b"
b : string , array "b" to check is identical to array "a"
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the current unit test name, if undefined the test index of the current case is used
Returns: bool, true if the assertion passes, false otherwise
new_case(case, name) Assign a new test case name, for the next set of unit tests. Usage: assert.new_case(case, 'My tests')
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
name : string, the case name for the next suite of tests
clear(case) Clear all stored unit tests from all cases. Usage: assert.clear(case)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
revert(case) Revert the previous unit test. Usage: = assert.revert(case)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
Returns: , tuple containing the msg and result of the reverted test
passed(case, revert) Check if the last unit test has passed. Usage: bool success = assert.passed(case)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
revert : bool, optionally revert the test
Returns: bool, true only if the test passed
failed(case, revert) Check if the last unit test has failed. Usage: bool failure = assert.failed(case)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
revert : bool, optionally revert the test
Returns: bool, true only if the test failed
report(case, verbose) Report the outcome of unit tests that fail. Usage: bool passed = assert.report(case)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
verbose : bool, optionally display full report that includes the outcome of all tests
Returns: bool, true only if all tests passed
unittest_assert(case) Assert module unit tests, for inclusion in parent script test suite. Usage: assert.unittest_assert(__ASSERTS)
Parameters:
case : string , the current test case and array of previous unit tests (__ASSERTS)
unittest(verbose) Run the assert module unit tests as a stand alone. Usage: assert.unittest()
Parameters:
verbose : bool, optionally toggle report to display the outcome of all unit tests